package com.tommy.jiami.ui;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Animatable2;
import android.graphics.drawable.AnimatedVectorDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Bundle;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.tommy.jiami.MyApplication;
import com.tommy.jiami.R;
import com.tommy.jiami.utils.Crypt;

import java.security.KeyStore;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class SettingPasswordActivity extends AppCompatActivity {

    //for characters
    TextInputLayout passwordLayout, passwordLayout2;

    //for fingerprint
    Button nextStep;
    FingerprintManager fingerprintManager;
    AnimatedVectorDrawable fingerprintDrawable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        switch (getIntent().getIntExtra("password_type", -1)) {
            case 0:
                initCharactersViews();
                break;
            case 1:
                initGraphicViews();
                break;
            case 2:
                initFingerPrintViews();
        }
    }

    public void initCharactersViews() {
        setContentView(R.layout.activity_characters_password);
        passwordLayout = (TextInputLayout) findViewById(R.id.password_layout);
        passwordLayout2 = (TextInputLayout) findViewById(R.id.password_layout_2);
    }

    public void confirm(View view) {
        String password = passwordLayout.getEditText().getText().toString();
        String password2 = passwordLayout2.getEditText().getText().toString();
        boolean hasError = false;
        if (password.length() < 4) {
            passwordLayout.setError(getString(R.string.password_too_short));
            hasError = true;
        }
        if (!password.equals(password2)) {
            passwordLayout2.setError(getString(R.string.password_not_accord));
            hasError = true;
        }
        if (!hasError) {
            try {
                String encrypted = Crypt.encryptString(password, Crypt.DEFAULT_PASSWORD);
                SharedPreferences.Editor editor=MyApplication.getSharedPreferences().edit();
                editor.putString("characters_password", encrypted);
                editor.putInt("password_type",0);
                editor.apply();
                setResult(RESULT_OK);
                Toast.makeText(this, R.string.set_password_succeed, Toast.LENGTH_SHORT).show();
                finish();
            } catch (Exception e) {
                Snackbar.make(getWindow().getDecorView(), getString(R.string.unknown_error, e.getLocalizedMessage()), Snackbar.LENGTH_LONG).show();
            }
        }
    }

    public void cancel(View view) {
        finish();
    }


    public void initGraphicViews() {

    }

    @TargetApi(23)
    public void initFingerPrintViews() {
        setContentView(R.layout.activity_fingerprint_password);
        nextStep=(Button)findViewById(R.id.next_step) ;
        nextStep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(SettingPasswordActivity.this,SettingPasswordActivity.class);
                intent.putExtra("password_type",0);
                intent.putExtra("standby",true);
                Toast.makeText(SettingPasswordActivity.this,R.string.set_standby_password,Toast.LENGTH_LONG).show();
                startActivityForResult(intent,1);
            }
        });
        ImageView imageView=(ImageView)findViewById(R.id.imageView);
        fingerprintDrawable=(AnimatedVectorDrawable)imageView.getDrawable();
        fingerprintDrawable.reset();
        fingerprintDrawable.registerAnimationCallback(new Animatable2.AnimationCallback() {
            @Override
            public void onAnimationEnd(Drawable drawable) {
                Snackbar.make(findViewById(R.id.root),R.string.verify_fingerprint_succeed,Snackbar.LENGTH_SHORT).show();
                nextStep.setEnabled(true);
            }
        });
        fingerprintManager=(FingerprintManager)getSystemService(FINGERPRINT_SERVICE);
        if(!fingerprintManager.hasEnrolledFingerprints())
            Snackbar.make(findViewById(R.id.root),R.string.no_fingerprint,Snackbar.LENGTH_LONG).show();
        else
            authenticateFingerprint();
    }


    @TargetApi(23)
    public void authenticateFingerprint() {
        try {
            KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
            keyStore.load(null);
            KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder("mykey",
                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);
            keyGenerator.init(builder.build());
            SecretKey key = keyGenerator.generateKey();
            Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
                    + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            fingerprintManager.authenticate(new FingerprintManager.CryptoObject(cipher), null, 0, new FingerprintManager.AuthenticationCallback() {
                @Override
                public void onAuthenticationError(int errorCode, CharSequence errString) {
                    Snackbar.make(getWindow().getDecorView(), errString, Snackbar.LENGTH_LONG).show();
                }

                @Override
                public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
                    fingerprintDrawable.start();
                }

                @Override
                public void onAuthenticationFailed() {
                    Snackbar.make(findViewById(R.id.root),R.string.verify_fingerprint_fail,Snackbar.LENGTH_SHORT).show();
                }
            }, null);
            Snackbar.make(findViewById(R.id.root), R.string.fingerprint_verify, Snackbar.LENGTH_LONG).show();
        } catch (Exception e) {
            Snackbar.make(findViewById(R.id.root), getString(R.string.unknown_error, e.getLocalizedMessage()), Snackbar.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode==RESULT_OK){
            Toast.makeText(this, R.string.set_password_succeed, Toast.LENGTH_SHORT).show();
            MyApplication.getSharedPreferences().edit().putInt("password_type",2).apply();
            setResult(RESULT_OK);
            finish();
        }
    }
}
